import React from 'react'
// import { Link } from 'react-router-dom'
import { 
  Row,
  Table,
  Input,
  Button,
  Form,
  Select,
  DatePicker,
  Modal,
  message,
  Icon
} from 'antd'
import api from '@/api'
import { ordetype } from '@/utils/type' // 商品类型
const { RangePicker } = DatePicker
const FormItem = Form.Item
const ButtonGroup = Button.Group
const Option = Select.Option

const { Column } = Table
// const confirm = Modal.confirm
class Orde extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      form: {
        id: '',
        shipments: false, // 发货弹窗
        saving: false// 发货弹窗
      },
      ordetype,
      tableselect: [], // 多选选中的数据
      morefilter: false, // 更多选项控制
      searchLoading: false,
      orders: [],
      orders_count: 0,
      filter: {
        limit: 13,
        page: 1,
        order_id: '', // 订单号
        receive_name: '', // 收货人
        mobile: '', // 手机号
        goods_name: '', // 商品名
        point: '', // 积分
        mobilllle: '', // 收货人
        status: '', // 状态
        price: '', // 价格
        express_num: '', // 快递单号
        created_start_at: '', // 开始日期
        created_end_at: '' // 结束日期
      }
    }
  }
  componentWillMount() {
    this.fetchList(1)
  }
  fetchList = async (_page) => {
    const filter =  this.state.filter
    filter.page = _page
    let logsdata = null
    let orders = []
    let orders_count = 0
    try{
      logsdata = await api.orde_getlist(filter)
    }catch{
      logsdata = {}
    }
    const data =  logsdata.data || {}
    if (data.status === 'success') {
      orders = data.data.orders.map((item, index) => {
        return {
          ...item,
          key: `${index}`
        }
      })
      orders_count = Number(data.data.orders_count)
    }
    this.setState({
      orders,
      orders_count,
      filter
    })
  }
  pickerChange = (date, dateString) => {
    const { filter } = this.state
    filter.created_start_at = dateString[0]
    filter.created_end_at = dateString[1]
    this.setState({filter})
  }
  // 搜索
  handleSubmit = (e) => {
    e.preventDefault()
    this.fetchList(1)
  }
  changeFilter = (e, val) => {
    const value = typeof(e) === 'object' ? e.target.value : e
    const {filter} = this.state
    filter[val] = value
    this.setState({filter})
  }
  goodsStrFun (_arr = []) {
    return _arr.map((item) => {
      const sku = item.sku.length > 0 ? item.sku.join('*') : ''
      return `${item.name}*${sku}*${item.count}`
    }).join('<br/>')
  }
  handleCancel = () => {
    const { form } = this.state
    form.shipments = false
    this.setState({ form })
  }
  shipmentsfun = (_id) => {
    const { form } = this.state
    form.id = _id
    form.shipments = !form.shipments
    this.setState({ form })
  }
  onSubmit = (e) => {
    e.preventDefault()
    this.props.form.validateFields((err, values) => {
      if (!err) {
        const { form } = this.state
        form.saving = true
        this.setState({ form })
        api.orde_elt(form.id, { express_name: values.express_name, express_num: values.express_num, status: 'SHIPPED' }).then(({ data }) => {
          form.saving = false
          form.shipments = false
            this.setState({ form })
            if (data.status === 'success') {
              this.fetchList()
              message.success('提交成功')
            }
          }).catch(() => {
            form.saving = false
            this.setState({ form })
          })
      }
    })
  }
   // 导出会员数据
   downloadExcel = () => {
    const _that = this
    Modal.confirm({
      title: '提示',
      content: '订单数据导出限制5000条一次, 是否继续?',
      onOk() {
        const hide = message.loading('Action in progress..', 0)
        const { filter } = _that.state
        api.orde_getlist({ ...filter, export: 1 }).then(({ data }) => {
          if (data.status === 'success') {
            hide()
            const _body = document.body || document.documentElement
            const aLink = document.createElement('a')
            let filename = data.data.path.split('/')
            filename = filename[filename.length - 1]
            if (filename) {
              aLink.setAttribute('download', filename)
            }
            aLink.href = api.baseURL + '/' + data.data.path
            _body.appendChild(aLink)
            aLink.click()
            _body.removeChild(aLink)
          } else {
            message.error(data.message)
          }
        })
      }
    })
  }
  render() {
    const {filter, orders_count, orders, morefilter, form} = this.state
    const { getFieldDecorator } = this.props.form
    return (
      <div>
        <Row
          gutter={20}
          className="mariya-filter-form"
          style={{height: 'auto'}}
          >
          <Form
            className="mariya-filter-form__entity"
            layout="inline"
            onSubmit={this.handleSubmit}
            style={{paddingLeft: '20px', minWidth: '1100px'}}
            >
            <FormItem>
              <Input
                size="default"
                placeholder="订单编号"
                value={filter.order_id}
                onChange={(e) => {this.changeFilter(e, 'order_id')}}
                allowClear
              />
            </FormItem>
            <FormItem>
              <Input
                size="default"
                placeholder="收货姓名"
                value={filter.receive_name}
                onChange={(e) => {this.changeFilter(e, 'receive_name')}}
                allowClear
              />
            </FormItem>
            <FormItem>
              <Input
                size="default"
                placeholder="手机号码"
                value={filter.mobile}
                onChange={(e) => {this.changeFilter(e, 'mobile')}}
                allowClear
              />
            </FormItem>
            <FormItem>
              <Input
                size="default"
                placeholder="商品"
                value={filter.goods_name}
                onChange={(e) => {this.changeFilter(e, 'goods_name')}}
                allowClear
              />
            </FormItem>
            <FormItem>
              <Input
                size="default"
                placeholder="价格"
                value={filter.price}
                onChange={(e) => {this.changeFilter(e, 'price')}}
                allowClear
              />
            </FormItem>
            <FormItem>
              <Button type="primary" htmlType="submit">搜索</Button>
            </FormItem>
            <FormItem>
              <Button type="primary"
                style={{ display: morefilter ? 'inline-block': 'none'}}
                onClick={(e) => {this.setState({morefilter: false})}} >更多<Icon type="up" /></Button> 
              <Button
                style={{ display: morefilter ? 'none' : 'inline-block'}}
                onClick={(e) => {this.setState({morefilter: true })}} >更多<Icon type="down" /></Button>
            </FormItem>
            <br/>
            <FormItem style={{ display: morefilter ? 'inline-block': 'none'}}>
              <Input
                size="default"
                placeholder="积分"
                value={filter.point}
                onChange={(e) => {this.changeFilter(e, 'point')}}
                allowClear
              />
            </FormItem>
            <FormItem style={{ display: morefilter ? 'inline-block': 'none'}}>
              <Input
                size="default"
                placeholder="快递单号"
                value={filter.express_num}
                onChange={(e) => {this.changeFilter(e, 'express_num')}}
                allowClear
              />
            </FormItem>
            <FormItem style={{ display: morefilter ? 'inline-block': 'none'}}>
              <Select onChange={(val) => { this.changeFilter(val, 'status') }} placeholder="请选择订单状态" allowClear style={{width: '140px'}}>
                {
                  ordetype.map((item) => {
                   return <Option key={item.value}>{item.label}</Option>
                  })
                }
              </Select>
            </FormItem>
            <FormItem style={{ display: morefilter ? 'inline-block': 'none'}}>
              <RangePicker onChange={this.pickerChange} allowClear />
            </FormItem>
          </Form>
          <div className="mariya-filter-form__group">
            <ButtonGroup>
              <Button className="m_l_10" onClick={this.downloadExcel} >导出</Button>
            </ButtonGroup>
          </div>
        </Row>
        <Row className="mariya-datagrid">
          <Table
            dataSource={orders}
            size="small"
            bordered
            pagination={{
              defaultCurrent: 1,
              total: orders_count,
              defaultPageSize: filter.limit
            }}
            onChange={({current}) => {this.fetchList(current)}}
            >
            <Column title="订单编号" dataIndex="id" key="id"/>
            <Column title="收货姓名"  key="name"
              render={(record) => (
                <span>{record.receive_info[0].name}</span>
              )}
            />
            <Column title="手机号码" key="mobile"
              render={(record) => (
                <span>{record.receive_info[0].mobile}</span>
              )}
            />
            <Column title="商品数量" key="address"
              render={(record) => (
                <span>{record.receive_info[0].address}</span>
              )}
            />
            <Column  title="商品" key="goods"
              render={(record) => (this.goodsStrFun(record.goods))}
            />
            <Column title="积分" dataIndex="point" key="point"/>
            <Column title="价格" dataIndex="price" key="price" />
            <Column title="快递" dataIndex="express_name" key="express_name" />
            <Column title="快递单号" dataIndex="express_num" key="express_num" />
            <Column title="快递状态" dataIndex="status_name" key="status_name" />
            <Column title="创建时间" dataIndex="created_at" key="created_at" />
            <Column title="更新时间" dataIndex="updated_at" key="updated_at" />
            <Column title="操作" key="actionbtn" width="180px"
              render={(record) => (
                <span>{
                  record.status === ordetype[1].value ? 
                  <Button size="small" onClick={() => {this.shipmentsfun(record.id)}}>发货</Button> : 
                  <span>{ record.status_name }</span>
                }</span>
              )}
              center
            />
          </Table>
        </Row>
        <Modal
          title="发货"
          width="600px"
          visible={form.shipments}
          confirmLoading={form.saving}
          onOk={this.onSubmit}
          onCancel={this.handleCancel}
        >
          <Form
            className="mariya-filter-form__entity"
            layout="inline"
            onSubmit={this.handleSubmit}
            style={{paddingLeft: '20px', minWidth: '1100px'}}
          >
            <FormItem>
              {
                getFieldDecorator('express_name', {
                  rules: [{ required: true, message: '请输入快递公司' }],
                })(
                  <Input size="default" allowClear placeholder="请输入快递公司"/>
                )
              }
            </FormItem>
            <FormItem>
              {
                getFieldDecorator('express_num', {
                  rules: [{ required: true, message: '请输入快递单号' }],
                })(
                  <Input size="default" allowClear placeholder="请输入快递单号"  />
                )
              }
            </FormItem>
          </Form>
        </Modal>
      </div>
    )
  }
}

export default Form.create({})(Orde)